package com.aaron.config;

import com.aaron.enums.SqlTypeEnum;
import com.aaron.pojo.Configuration;
import com.aaron.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        Map<String, MappedStatement> mappedStatementMap = new HashMap<>(16);

        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            System.out.println(element.getName());
            String type = element.getName();
            this.createMappedStatement(type, element, namespace, mappedStatementMap);
        }
        configuration.setMappedStatementMap(mappedStatementMap);
        System.out.println("断点");
    }


    private void createMappedStatement(String type, Element element, String namespace, Map<String, MappedStatement> mappedStatementMap) {
        String id = element.attributeValue("id");
        String resultType = element.attributeValue("resultType");
        String parameterType = element.attributeValue("parameterType");
        String sqlText = element.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setParameterType(parameterType);
        mappedStatement.setResultType(resultType);
        mappedStatement.setSql(sqlText);
        mappedStatement.setSqlType(SqlTypeEnum.valueOf(type));
        String key = namespace + "." + id;
        mappedStatementMap.put(key, mappedStatement);
    }
}
